<template>
	<view>
		<view class="content">
			<view class="input-left">
				<input v-model="a" type="digit" placeholder="a" style="text-align: center;" />
				<view class="line"></view>
				<input v-model="b" type="digit" placeholder="b" style="text-align: center;" />
			</view>

			<view class="input-left" style="width: 100rpx;text-align: center;">等于</view>

			<view class="input-left">
				<input v-model="c" type="digit" placeholder="c" style="text-align: center;" @input="calculateD" />
				<view class="line"</view>
				<input v-model="d" type="digit" placeholder="d" style="text-align: center;" @input="calculateC" />
			</view>
		</view>
		
		<button class="submit" @click="calculate">计算比例</button>

		<view v-if="simplifiedRatio" class="content">
			简化比例：{{ simplifiedRatio }}
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady
	} from '@dcloudio/uni-app'
	// 定义响应式变量
	const a = ref(null); // 比例的第一项
	const b = ref(null); // 比例的第二项
	const c = ref(null); // 结果的第一项
	const d = ref(null); // 结果的第二项
	const simplifiedRatio = ref(''); // 简化后的比例

	// 计算最大公约数（用于简化比例）
	const gcd = (x, y) => {
		while (y) {
			let t = y;
			y = x % y;
			x = t;
		}
		return x;
	};

	// 简化比例
	const simplify = () => {
		if (a.value && b.value) {
			const commonDivisor = gcd(Math.abs(a.value), Math.abs(b.value));
			const simplifiedA = a.value / commonDivisor;
			const simplifiedB = b.value / commonDivisor;
			simplifiedRatio.value = `${simplifiedA}:${simplifiedB}`;
		} else {
			simplifiedRatio.value = '';
		}
	};

	// 当a或b变化时自动简化比例
	watch([a, b], ()=>{
		c.value = null
		d.value = null
		simplify()
	});

	// 根据c计算d
	const calculateD = () => {
		if (a.value && b.value && c.value) {
			d.value = (b.value * c.value) / a.value;
		}
	};

	// 根据d计算c
	const calculateC = () => {
		if (a.value && b.value && d.value) {
			c.value = (a.value * d.value) / b.value;
		}
	};

	// 计算比例的主函数
	const calculate = () => {
		// 根据已有值决定计算哪个值
		if (a.value && b.value && c.value && !d.value) {
			calculateD();
		} else if (a.value && b.value && d.value && !c.value) {
			calculateC();
		}
	}
</script>

<style>
	@import "proportion.css"
</style>